<template>
  <a-modal
    :visible="visible"
    title="新建上传"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="formRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol">
      <a-form-item ref="reName" label="资源名称" name="reName">
        <a-input v-model:value="formState.reName"/>
      </a-form-item>
      <a-form-item label="资源模块" name="reModule">
        <a-select v-model:value="formState.reModule">
          <a-select-option :value="post.id" v-bind:key="index" v-for="(post,index) in state.posts">{{post.label}}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="上传文件" name="deptId">
        <a-upload
          v-model:file-list="fileList"
          name="file"
          action="http://192.168.0.145:9292/api/sys/upload/uploadFiles"
          :headers="headers"
          @change="handleChange"
          :remove="removes"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            Click to Upload
          </a-button>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import {message} from 'ant-design-vue';
import {defineComponent, reactive, ref, toRaw} from "vue";
import { list } from "@/api/module/post";
import {deleteFiles, getModule, saveResource} from "../../../api/module/resource";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
    },
  },
  emit: ["close"],
  setup(props, context) {
    const fileList = ref([]);
    const loading = ref(false);
    const imageUrl = ref('');
    const formRef = ref();

    const state = reactive({
      posts: [],
    })

    const formState = reactive({
      reAddress:"",
      size:""
    });

    const formRules = {
      reName: [{required: true, message: '请输入资源名称', trigger: 'blur'}],
      reModule: [{required: true, message: '请选择资源模块', trigger: 'blur'}]
    };


    const loadPost = () => {
      getModule({}).then((response)=>{
        state.posts = response.data;
      })
    }
    // 新增资源保存
    const submit = (e) => {
      formRef.value.validate().then(() => {
        saveResource(toRaw(formState)).then((response) => {
          if (response.success) {
            message.success({content: '保存成功', duration: 1}).then(() => {
              cancel();
            });
          } else {
            message.error({content: response.msg, duration: 1}).then(() => {
            });
          }
        })
      }).catch(error => {
        console.log('error', error);
      });
    };

    const cancel = (e) => {
      formRef.value.resetFields();
      context.emit("close", false);
    };


    /// 加载 资源模块
    loadPost();

    // 上传文件改变时的状态
    const handleChange = info => {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }

      if (info.file.status === 'done') {
        message.success(`${info.file.name} 已上传`);
        formState.reAddress = info.file.response.data.url
        formState.size = info.file.response.data.size
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败.`);
      }
    };

    // token 所需
    const tokenKey = localStorage.getItem("token_key");
    const token = localStorage.getItem("token")

    const headers = {
      "Authorization": token,
      "Authorization-key": tokenKey
    };
    // 点击删除按钮
    const removes = file=>{
      console.log("---------------------------------",file)
      deleteFiles(file.response.data.url).then((response) => {
        if (response.success) {
          message.success({content: '删除成功', duration: 1}).then(() => {
            // 还需做删除之前上传的
            fileList.value = ""
          });
        } else {
          message.error({content: response.msg, duration: 1});
        }
      })
    };

    return {
      state,
      submit,
      cancel,
      formRef,
      formState,
      formRules,

      labelCol: {span: 6},
      wrapperCol: {span: 18},

      replaceFields: {children: 'children', title: 'name', key: 'id', value: 'id'},
      // 下面是上传文件资源所用接口
      fileList,
      loading,
      imageUrl,
      handleChange,
      headers,
      removes,
    };


  },
});
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
